#include "dvb_array.h"
#include <string.h>
#include <stdlib.h>
#include <math.h>

uint32_t CountOfDvbArray(DVB dvArray[])
{
	uint32_t count = 0;
	while(dvArray[count] != EODVB) {
		count++;
	}
	return(count);
}

bool DvbArray2String(char strBuf[], uint32_t bufSize, DVB dvArray[])
{
	char dvBuf[DVB_BUF_SIZE];
	int i = 0;
	uint32_t convertedLength = 0;
	uint32_t addingStrLen;
	
	strcpy(strBuf, "");
	while(dvArray[i] != EODVB) {
		Dvb2String(dvBuf, dvArray[i]);
		addingStrLen = strlen(dvBuf);
		if (convertedLength + 1 + addingStrLen + 1 > bufSize) {
			return(false);
		}

		if(i != 0) {
			strcat(strBuf, ",");
			convertedLength += 1;
		}
		strcat(strBuf, dvBuf);
		convertedLength += addingStrLen;
		i++;
	}
	return(true);
}

uint32_t ParseCountOfNumber(const char* numberStr)
{
	uint32_t count = 0;
	const char* pstr = numberStr;
	
	while (true) {
		char c = *pstr++;
		if (c == '\0') {
			count++;
			break;
		}
		else if (c == ',') {
			count++;
		}
		else if ((c >= '0' && c <= '9') || c == '.' || c == '-') {
			continue;
		}
	}
	return(count);
}

bool String2DvbArray(DVB dvArray[], uint32_t arrayLen, const char *numberStr)
{
	char dvBuf[DVB_BUF_SIZE];
	int i = 0;
	int bi = 0;
	uint32_t count = 0;
	bool convertedAll = false;
	
	while(count < arrayLen - 1) {
		char c = numberStr[i++];
		if(c == '\0') {
			dvBuf[bi] = '\0';
			dvArray[count++] = String2Dvb(dvBuf);
			convertedAll = true;
			break;
		}
		else if(c == ',') {
			dvBuf[bi] = '\0';
			dvArray[count++] = String2Dvb(dvBuf);
			bi = 0;
		}
		else if((c >= '0' && c <= '9') || c == '.' || c == '-') {
			dvBuf[bi++] = c;
			if(bi == DVB_BUF_SIZE) {	
				break;
			}
		}
	}
	dvArray[count] = EODVB;
	return(convertedAll);
}

void FloatArray2DvbArray(DVB dvArray[], float fArray[], uint32_t n, int digits)
{
	uint32_t i;
	
	for (i = 0; i < n; i++) {
		dvArray[i] = ValidFloat2Dvb(fArray[i], digits);
	}
	dvArray[n] = EODVB;
}

void IntArray2DvbArray(DVB dvArray[], long iArray[], uint32_t n)
{
	uint32_t i;
	
	for (i = 0; i < n; i++) {
		dvArray[i] = Int2Dvb(iArray[i]);
	}
	dvArray[n] = EODVB;
}

uint32_t DvbArray2FloatArray(float fArray[], DVB dvArray[])
{
	uint32_t i = 0;
	
	while (dvArray[i] != EODVB) {
		fArray[i] = Dvb2Float(dvArray[i]);
		i++;
	}
	return(i);
}

uint32_t DvbArray2IntArray(long iArray[], DVB dvArray[])
{
	uint32_t i = 0;
	
	while (dvArray[i] != EODVB) {
		iArray[i] = Dvb2Int(dvArray[i]);
		i++;
	}
	return(i);
}
